//
//  CLOAuthViewController.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/10.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
//微博appkey
let WeiboAppkey = "2084129329"
//微博appsecret
let weiboAppSecret = "45f4400d7ec6802cb5626ad192e2bb8d"
//微博回调地址
let WeiboRedirect_ur = "http://www.itcast.cn"

class CLOAuthViewController: UIViewController {
    
    
    // MARK:    --懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    //自定义视图
    override func loadView() {
        webView.delegate = self
        //默认不透明 改为透明
        webView.opaque = false
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        requestOAuthLogin()
        setUpUI()
    }
    // MARK:  请求登录界面
    private func requestOAuthLogin (){
        //请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppkey)&redirect_uri=\(WeiboRedirect_ur)"
        //准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //加载请求
        webView.loadRequest(request)
    }
    // MARK:  加载界面
    private func setUpUI (){
        
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAvtion")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self , action: "autoFillAction")
        
    }
    // MARK:  导航栏按钮点击事件
    @objc private func cancelAvtion(){
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true , completion: nil)
    
    }
    @objc private func autoFillAction(){
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'jimmychenliang@sina.com'; document.getElementById('passwd').value = '15607103133'")
    }
//    // MARK:  通过授权码 获取accessToken
//    private func requestAccessToken(code :String){
//        CLNetWorkingTool.sharedTool.requestAccessToken(code) { (response, error) -> () in
//            if error != nil {
//                return
//            }
//            guard let dic = response as? [String :AnyObject] else {
//                return
//            }
//            let userAccount = CLUserAccount(dic: dic )
//            
//            self.requestUserInfo(userAccount)
//        }
//    }
//    // MARK:  获取用户信息
//    func requestUserInfo(userAccount :CLUserAccount){
//        CLNetWorkingTool.sharedTool.requestUserInfo(userAccount) { (response, error) -> () in
//            if error != nil {
//                return
//            }
//            guard let dic = response as? [String :AnyObject] else {
//                return
//            }
//            let name = dic["name"]
//            let avatar_large = dic["avatar_large"]
//            //设置用户名和头像
//            userAccount.name = name as? String
//            userAccount.avatar_large = avatar_large as? String
//            //保存用户对象
//            userAccount.saveUserAccount()
//            
//        }
//    }
//    
}

extension CLOAuthViewController:UIWebViewDelegate {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL else {
            return false
        }
        if !url.absoluteString.hasPrefix(WeiboRedirect_ur){
            return true
        }
        if let query = url.query where query.hasPrefix ("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            
//            requestAccessToken(code)
            CLUserAccountViewModel.sharedUserAccount.requestAccessToken(code , callback: { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    self.dismissViewControllerAnimated(false  , completion: { () -> Void in
                        //发送通知,释放资源
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                }else {
                    print ("登录失败")
                }
            })
        }else {
            //进入取消回调页
            dismissViewControllerAnimated(true , completion: nil)
        }
        return false
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //完成加载
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
}





